package com.example.housemanage.revise

import android.app.DatePickerDialog
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.viewModelScope
import com.example.housemanage.HouseManageViewModel
import com.example.housemanage.databinding.ActivityReviseBinding
import com.example.housemanage.entity.HouseManageEntityItem
import com.example.lib_base.http.HttpType
import com.example.lib_base.http.NotWorkFactory
import com.example.lib_base.mvvm.BaseActivity
import com.example.lib_base.mvvm.BaseViewModel
import com.example.lib_base.mvvm.Res
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Path
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

// 定义API接口
interface PropertyApiService {
    @GET("api/properties/{id}")
    suspend fun getProperty(@Path("id") id: String): Res<HouseManageEntityItem>
}

@AndroidEntryPoint
class ReviseActivity : BaseActivity<ActivityReviseBinding, HouseManageViewModel>() {
    
    // 添加扩展函数，使用BaseViewModel中的httpRequest函数
    private fun <T> httpRequest(
        requestCall: suspend () -> Res<T>?,
        onSuccess: (T) -> Unit,
        onError: ((String) -> Unit)? = null
    ) {
        vm.viewModelScope.launch {
            try {
                val res = requestCall()
                if (res == null) {
                    val errorMsg = "请求返回空数据"
                    onError?.invoke(errorMsg)
                    return@launch
                }
                
                if (res.code == 200) {
                    onSuccess(res.data)
                } else {
                    val errorMsg = "请求失败: ${res.msg}"
                    Toast.makeText(this@ReviseActivity, errorMsg, Toast.LENGTH_SHORT).show()
                    onError?.invoke(errorMsg)
                }
            } catch (e: Exception) {
                val errorMsg = "请求异常: ${e.message}"
                Toast.makeText(this@ReviseActivity, errorMsg, Toast.LENGTH_SHORT).show()
                onError?.invoke(errorMsg)
            }
        }
    }
    
    private var propertyId: Int = 0
    // 使用NotWorkFactory创建带有TOKEN认证的API服务实例
    private val apiService: PropertyApiService by lazy {
        NotWorkFactory.getRetrofit(HttpType.TOKEN).create(PropertyApiService::class.java)
    }
    private var currentProperty: HouseManageEntityItem? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        // 获取传递的房屋ID - 在super.onCreate之前获取，确保在initData调用前已经准备好
        propertyId = intent.getIntExtra("property_id", 0)
        
        super.onCreate(savedInstanceState)
        
        // 检查propertyId是否有效
        if (propertyId == 0) {
            Toast.makeText(this, "房屋ID不能为空", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        
        // 设置标题栏返回按钮
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }
    
    override fun initView() {
        // 设置日期选择器
        binding.etRentDate.setOnClickListener {
            showDatePicker()
        }
        
        // 设置状态切换监听
        binding.rgStatus.setOnCheckedChangeListener { group, checkedId ->
            val isRented = checkedId == binding.rbRented.id
            updateInputFieldsVisibility(isRented)
        }
        
        // 设置提交按钮点击事件
        binding.btnSubmit.setOnClickListener {
            submitPropertyUpdate()
        }
    }

    override fun initData() {
        // 获取房屋详情
        fetchPropertyDetails()
    }
    
    private fun fetchPropertyDetails() {
        binding.btnSubmit.isEnabled = false
        
        httpRequest({
            apiService.getProperty(propertyId.toString())
        }, { property ->
            if (property != null) {
                currentProperty = property
                displayPropertyDetails(property)
                binding.btnSubmit.isEnabled = true
            } else {
                showError("获取房屋详情失败：数据为空")
            }
        }, {
            showError("获取房屋详情失败：请求异常")
        })

    }
    
    private fun displayPropertyDetails(property: HouseManageEntityItem) {
        // 显示基本信息
        binding.tvRoomNumber.text = property.id.toString()
        binding.tvRegion.text = property.regionName
        binding.tvArea.text = "${property.area} m²"
        binding.tvEnterprise.text = property.enterpriseName.ifEmpty { "暂无" }
        binding.tvRentDate.text = property.rentDate.ifEmpty { "暂无" }
        
        // 显示当前状态
        val statusText = if (property.rented) "已租" else "出租"
        val statusColor = if (property.rented) "#FF4081" else "#4CAF50"
        binding.tvCurrentStatus.text = statusText
        binding.tvCurrentStatus.setTextColor(android.graphics.Color.parseColor(statusColor))
        
        // 设置默认选中状态
        if (property.rented) {
            binding.rbRented.isChecked = true
        } else {
            binding.rbAvailable.isChecked = true
        }
        
        // 填充企业信息
        binding.etEnterprise.setText(property.enterpriseName)
        binding.etEnterpriseId.setText(property.enterpriseId.toString())
        binding.etRentDate.setText(property.rentDate)
        
        // 更新输入框可见性
        updateInputFieldsVisibility(property.rented)
    }
    
    private fun updateInputFieldsVisibility(isRented: Boolean) {
        val visibility = if (isRented) View.VISIBLE else View.GONE
        binding.tilEnterprise.visibility = visibility
        binding.tilEnterpriseId.visibility = visibility
        binding.tilRentDate.visibility = visibility
    }
    
    private fun showDatePicker() {
        val calendar = Calendar.getInstance()
        val currentDate = binding.etRentDate.text.toString()
        
        if (currentDate.isNotEmpty()) {
            try {
                val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                val date = sdf.parse(currentDate)
                if (date != null) {
                    calendar.time = date
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)
        
        DatePickerDialog(this, { _, selectedYear, selectedMonth, selectedDay ->
            val selectedDate = "$selectedYear-${selectedMonth + 1}-$selectedDay"
            binding.etRentDate.setText(selectedDate)
        }, year, month, day).show()
    }
    
    private fun submitPropertyUpdate() {
        if (currentProperty == null) {
            showError("房屋信息未加载完成，请稍后再试")
            return
        }
        
        val isRented = binding.rbRented.isChecked
        
        // 验证输入
        if (isRented) {
            if (binding.etEnterprise.text.toString().isEmpty()) {
                binding.tilEnterprise.error = "请输入企业名称"
                return
            } else {
                binding.tilEnterprise.error = null
            }
            
            if (binding.etEnterpriseId.text.toString().isEmpty()) {
                binding.tilEnterpriseId.error = "请输入企业ID"
                return
            } else {
                binding.tilEnterpriseId.error = null
            }
            
            if (binding.etRentDate.text.toString().isEmpty()) {
                binding.tilRentDate.error = "请选择租赁日期"
                return
            } else {
                binding.tilRentDate.error = null
            }
        }
        
        // 创建更新对象
        val updatedProperty = HouseManageEntityItem(
            id = propertyId,
            area = currentProperty!!.area,
            regionId = currentProperty!!.regionId,
            regionName = currentProperty!!.regionName,
            rented = isRented,
            enterpriseId = if (isRented) binding.etEnterpriseId.text.toString().toInt() else 0,
            enterpriseName = if (isRented) binding.etEnterprise.text.toString() else "",
            rentDate = if (isRented) binding.etRentDate.text.toString() else ""
        )
        
        // 调用ViewModel更新房屋信息
        vm.updateProperty(updatedProperty).observe(this, Observer { result ->
            if (result) {
                Toast.makeText(this, "房屋状态更新成功", Toast.LENGTH_SHORT).show()
                // 刷新数据
                fetchPropertyDetails()
            } else {
                showError("房屋状态更新失败")
            }
        })
    }
    
    private fun showError(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
        binding.btnSubmit.isEnabled = true
    }
    
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }
    //防止内存泄漏
    override fun onDestroy() {
        super.onDestroy()
        vm.deletePropertyResult.removeObservers(this)
        vm.propertiesResult.removeObservers(this)
        vm.addPropertyResult.removeObservers(this)
        vm.updatePropertyResult.removeObservers(this)

    }
}